import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.state.user.token) {
      config.headers['Authorization'] = store.state.user.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    // token过期被动处理
    if (error.response.status === 401) {
      Message.error('token过期，请重新登录')
      store.dispatch('user/logout')
    }
    return Promise.reject(error)
  }
)

export default service
